package com.maddox.relax.helper.launcher;

import android.content.Intent;
import android.os.Bundle;
import android.util.SparseArray;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.util.Random;

public class MRouteFragment extends Fragment {
    //存储回调
    private SparseArray<MLauncher.CallBack> mCallbacks = new SparseArray<>();
    private Random random = new Random();

    public MRouteFragment() {

    }

    public static MRouteFragment newInstance() {
        return new MRouteFragment();
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //在Activity重新创建时不进行onDetach
        setRetainInstance(true);
    }

    public void startActivityForResult(Intent intent, MLauncher.CallBack callBack) {
        int requestCode = generateCode();
        //存储请求码以及对应的请求结果回调
        mCallbacks.put(requestCode, callBack);
        //发起请求
        startActivityForResult(intent, requestCode);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        MLauncher.CallBack callBack = mCallbacks.get(requestCode);
        mCallbacks.remove(requestCode);
        if (callBack != null) {
            callBack.onActivityResult(resultCode, data);
        }

    }

    //自动生成一个请求码
    private int generateCode() {
        int requestCode = 0;
        int tryCount = 0;
        do {
            requestCode = random.nextInt(0x0000ffff);
            tryCount++;

        } while (mCallbacks.indexOfKey(requestCode) >= 0 && tryCount < 10);

        return requestCode;
    }
}
